package com.chuangshu.chuangshuteam.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chuangshu.chuangshuteam.config.BaseContext;
import com.chuangshu.chuangshuteam.dto.CommentsDTO;
import com.chuangshu.chuangshuteam.dto.Result;
import com.chuangshu.chuangshuteam.entity.Comments;
import com.chuangshu.chuangshuteam.entity.Posts;
import com.chuangshu.chuangshuteam.service.CommentsService;
import com.chuangshu.chuangshuteam.service.PostsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author k
 * @since 2025-09-21
 */
@RestController
@RequestMapping("/comments")
public class CommentsController {

    @Autowired
    private CommentsService commentsService;
    
    @Autowired
    private PostsService postsService;

    /**
     * 发布评论
     * @param postId 帖子ID
     * @param content 评论内容
     * @param parentCommentId 父评论ID（可选，用于回复评论）
     * @return 评论结果
     */
    @PostMapping("/posts/{postId}")
    public Result postComment(@PathVariable Long postId, 
                              @RequestParam String content,
                              @RequestParam(required = false) Long parentCommentId) {
        // 检查帖子是否存在
        Posts post = postsService.getById(postId);
        if (post == null) {
            return Result.fail("帖子不存在");
        }
        
        // 检查内容是否为空
        if (content == null || content.trim().isEmpty()) {
            return Result.fail("评论内容不能为空");
        }
        
        // 如果是回复评论，检查父评论是否存在
        if (parentCommentId != null) {
            Comments parentComment = commentsService.getById(parentCommentId);
            if (parentComment == null) {
                return Result.fail("回复的评论不存在");
            }
        }
        
        // 创建评论
        Comments comment = new Comments();
        comment.setPostId(postId);
        comment.setAuthorId(BaseContext.getCurrentId());
        comment.setContent(content);
        comment.setParentCommentId(parentCommentId);
        comment.setCreatedAt(LocalDateTime.now());
        comment.setUpdatedAt(LocalDateTime.now());
        
        // 保存评论
        commentsService.save(comment);
        
        return Result.ok(comment);
    }
    
    /**
     * 获取帖子的评论列表（分页）
     * @param postId 帖子ID
     * @param page 页码
     * @param size 每页大小
     * @return 评论列表
     */
    @GetMapping("/posts/{postId}")
    public Result getCommentsByPostId(@PathVariable Long postId,
                                      @RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "10") Integer size) {
        // 检查帖子是否存在
        Posts post = postsService.getById(postId);
        if (post == null) {
            return Result.fail("帖子不存在");
        }
        
        // 分页查询评论
        Page<Comments> commentsPage = new Page<>(page, size);
        LambdaQueryWrapper<Comments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comments::getPostId, postId)
                .isNull(Comments::getDeletedAt)  // 只查询未删除的评论
                .orderByAsc(Comments::getCreatedAt);  // 按创建时间升序排列
        
        Page<Comments> result = commentsService.page(commentsPage, queryWrapper);
        List<Comments> records = result.getRecords();
        List<CommentsDTO> commentsDTOList = new ArrayList<>();
        for (Comments comment : records) {
            CommentsDTO commentsDTO = new CommentsDTO();
            commentsDTO.setComments(comment);
            LambdaQueryWrapper<Comments> commentsLambdaQueryWrapper = new LambdaQueryWrapper<>();
             commentsLambdaQueryWrapper.eq(Comments::getParentCommentId, comment.getId());
            List<Comments> list = commentsService.list(commentsLambdaQueryWrapper);
            commentsDTO.setReplies(list);
            commentsDTOList.add(commentsDTO);
        }
        Page<CommentsDTO> commentsDTOPage = new Page<>();
        commentsDTOPage.setRecords(commentsDTOList);
        commentsDTOPage.setTotal(result.getTotal());
        commentsDTOPage.setPages(result.getPages());
        commentsDTOPage.setCurrent(page);
        return Result.ok(commentsDTOPage);
    }
    
    /**
     * 删除评论
     * @param commentId 评论ID
     * @return 删除结果
     */
    @DeleteMapping("/{commentId}")
    public Result deleteComment(@PathVariable Long commentId) {
        // 检查评论是否存在
        Comments comment = commentsService.getById(commentId);
        if (comment == null) {
            return Result.fail("评论不存在");
        }
        
        // 检查权限（只有评论作者可以删除）
        if (!comment.getAuthorId().equals(BaseContext.getCurrentId())) {
            return Result.fail("没有权限删除该评论");
        }
        
        // 软删除评论（设置删除时间）
        comment.setDeletedAt(LocalDateTime.now());
        comment.setUpdatedAt(LocalDateTime.now());
        commentsService.updateById(comment);
        
        return Result.ok("评论删除成功");
    }
    
    /**
     * 获取用户的所有评论
     * @param userId 用户ID
     * @param page 页码
     * @param size 每页大小
     * @return 评论列表
     */
    @GetMapping("/users/{userId}")
    public Result getCommentsByUserId(@PathVariable Long userId,
                                      @RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "10") Integer size) {
        // 分页查询评论
        Page<Comments> commentsPage = new Page<>(page, size);
        LambdaQueryWrapper<Comments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comments::getAuthorId, userId)
                .isNull(Comments::getDeletedAt)  // 只查询未删除的评论
                .orderByDesc(Comments::getCreatedAt);  // 按创建时间降序排列
        
        Page<Comments> result = commentsService.page(commentsPage, queryWrapper);
        
        return Result.ok(result);
    }
}